sdApp.controller("QuestionController", function ($rootScope, $scope, questionData, $http, transformRequestAsFormPost, fillerDataSrv) {

    $scope.questionData = questionData;
    $scope.fillers = {};
    var setActive = function (selectedOption) {
        angular.forEach($scope.questionData.answers, function (option) {
            option.active = option.answer_id == selectedOption;
        });


    }
    
	
    
	$scope.getComments = function(){
        var request = $http({
            method: "get",
            url: $rootScope.urlPrefix + "/comments/" + $scope.questionData.question_id,
            headers:{
                "Content-Type":"application/x-www-form-urlencoded"
            }
        });
        request.success(
            function(data){
                console.log('comments ' +data.records);
                if(data.records.length > 0){
                    $scope.commentsData = data.records;
                }
            }
        )
    }
    $scope.getComments();
    
    $scope.postComment = function(){
        //console.log($rootScope.stateCard.userId)
        var request = $http({
            method: "post",
            transformRequest: transformRequestAsFormPost,
            url: $rootScope.urlPrefix + "/comment",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            data: {
                questionid: $scope.questionData.question_id,
                comment: $scope.addComment,
                userid: $rootScope.stateCard.userId,
                username: $rootScope.stateCard.firstName,
            }
        });

        request.success(
                function (data) {
                    console.log(data);
                    if (data.result == 'success') {
                        $scope.getComments();
                    }
                }
        ); 
    }
    
    $scope.decide = function (option) {
        console.log(option);
        var request = $http({
            method: "post",
            transformRequest: transformRequestAsFormPost,
            url: $rootScope.urlPrefix + "/decide",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            data: {
                questionid: $scope.questionData.question_id,
                answerid: option.answer_id
            }
        });

        request.success(
                function (data) {
                    console.log(data);
                    if (data.result == 'success') {
                        $scope.questionData.decision.decision_made = true;
                        $scope.questionData.decision.answer_id = data.answer_id;
                    }
                }
        );
    }

    $scope.fillers.topQuestions = fillerDataSrv.topQuestions();
    $scope.fillers.votes = fillerDataSrv.yourVotes();


    $scope.castVote = function (option) {
        if (!$scope.questionData.decision.decision_made) {
            if ($rootScope.stateCard.userId && parseInt($rootScope.stateCard.userId) > 0) {
                console.log(option);

                var request = $http({
                    method: "post",
                    transformRequest: transformRequestAsFormPost,
                    url: $rootScope.urlPrefix + "/vote",
                    headers: {
                        "Content-Type": "application/x-www-form-urlencoded"
                    },
                    data: {
                        login: $rootScope.stateCard.userId,
                        questionvoterid: $scope.questionData.postedBy.id,
                        questionid: $scope.questionData.question_id,
                        answerid: option.answer_id
                    }
                });

                // Store the data-dump of the FORM scope.
                request.success(
                        function (data) {
                            console.log(data);
                            if (data.result == 'success') {
                                $scope.questionData.answers = data.answers;
                                setActive(data.answer_id);
                            }
                            else{
                                alert(data.message);
                            }
                        }
                );
            } else {
                console.log('You have to login');
                alert('You have to login to cast a vote');
            }
        } else {
            alert('decision already made');
        }
    }
	
	/* Chart Code */
	var jsonobject = questionData.answers;

	var alphabhets = 'abcdefghijklmnopqrstuvwxyz';
	
	var margin = {top: 20, right: 30, bottom: 30, left: 40}, width = 500 - margin.left - margin.right, 	height = 300 - margin.top - margin.bottom;
	 
	var x = d3.scale.ordinal().rangeRoundBands([0, width], .1);
	 
	var y = d3.scale.linear().range([height, 0]);
	 
	var xAxis = d3.svg.axis().scale(x).orient("bottom");
	 
	var yAxis = d3.svg.axis().scale(y).orient("left");
	 
	var chart = d3.select(".chart")
	.attr("width", width + margin.left + margin.right)
	.attr("height", height + margin.top + margin.bottom)
	.append("g")
	.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
	 
	var data;
	 
	$('#tooltip').addClass('hidden');
	 
	//if (error) return console.warn(error);
	 
	data = jsonobject;
	 
	x.domain(data.map(function(d, i) { 
		//return d.letter;
		return alphabhets.charAt(i);
	}));
	 
	y.domain([0, d3.max(data, function(d) { return d.votes; })]);
	 
	chart.append("g")
	.attr("class", "x axis")
	.attr("transform", "translate(0," + height + ")")
	.call(xAxis);
	 
	chart.append("g")
	.attr("class", "y axis")
	.call(yAxis);
	 
	chart.selectAll(".bar")
	.data(data)
	.enter()
	.append("rect")
	.attr("class", "bar")
	.attr("id", function(d, i) { return 'bar'+alphabhets.charAt(i);})
	.attr("x", function(d, i) { return x(alphabhets.charAt(i)); })
	.attr("y", function(d) { return y(d.votes); })
	.attr("height", function(d) { return height - y(d.votes); })
	.attr("width", x.rangeBand())
	//.attr("fill", function(d) { return "rgb(" + Math.round(d.votes * 1000) + ",10, 100)"; })
	.attr("fill", '#eb1f27')
	 
	 //-- on click
	/* .on("click", function(d){
		window.open(d.fb, '_blank', 'location=yes,height=600,width=960,scrollbars=yes,status=yes');
	}) */
	
	
	//-- on Mouse over
	.on("mouseover", function(d) {
		d3.select(this)
		.transition()
		.duration(50)
		.attr("fill", "#23a0da");
	 
		//Get this bar's x/y values, then augment for the tooltip
		var xPosition = parseFloat(d3.select(this).attr("x")) + x.rangeBand() / 2;
		var yPosition = parseFloat(d3.select(this).attr("y")) / 2 + height / 2;
	 
		//Update the tooltip position and value
		d3.select("#tooltip")
		.style("left", xPosition + "px")
		.style("top", yPosition + "px")
		.select("#value")
		.text(d.votes);
		 
		d3.select("#alphabet")
		.text(d.answer);
		 
		/* d3.select("#pic")
		.attr("src","img/"+d.pic); */
	 
		//Show the tooltip
		d3.select("#tooltip").classed("hidden", false);
	})
	
	
	//-- on mouse out
	.on("mouseout", function() {
		d3.select(this)
		.transition()
		.delay(100)
		.duration(250)
		//.attr("fill", function(d) { return "rgb(" + Math.round(d.votes * 1000) + ",10, 100)"; })
		.attr("fill", "#eb1f27")
	 
		//Hide the tooltip
		d3.select("#tooltip").classed("hidden", true);
	 
	})
	
	//-- 
	.append("title")
	.text(function(d, i) {  return alphabhets.charAt(i) + " value is " + d.votes;});
 


	/* Chart Code Ends */
	
});
